package com.cust.sky.controller.user;


import com.cust.sky.constant.MessageConstant;
import com.cust.sky.context.BaseContext;
import com.cust.sky.entity.AddressBook;
import com.cust.sky.service.AddressBookService;
import com.cust.sky.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 地址簿 前端控制器
 * </p>
 *
 * @author lei
 * @since 2024-07-10
 */
@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "C端地址簿接口")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public R<List<AddressBook>> list() {
//        AddressBook addressBook = new AddressBook();
//        addressBook.setUserId(BaseContext.getCurrentId());
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList = addressBookService.findAddressBookByUserId(userId);
        return R.success(addressBookList);
    }

    /**
     * 新增地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址")
    public R save(@RequestBody AddressBook addressBook) {
        addressBookService.saveAddressBook(addressBook);
        return R.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public R<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        return R.success(addressBook);
    }

    /**
     * 修改地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    @ApiOperation("修改地址")
    public R update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return R.success();
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public R setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return R.success();
    }

    /**
     * 根据id删除地址
     *
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public R deleteById(Long id) {
        addressBookService.removeById(id);
        return R.success();
    }

    /**
     * 查询当前用户的默认地址
     */
    @GetMapping("default")
    @ApiOperation("查询当前用户的默认地址")
    public R<AddressBook> getDefault() {
        AddressBook addressBook = addressBookService.getDefault();
        if (addressBook == null) {
            return R.error(MessageConstant.DEFAULT_ADDRESSBOOK_NOT_FOUND);
        }
        return R.success(addressBook);
    }

}

